#include "mutex.h"
#include <iostream>
#include <errno.h>

namespace concurrent {

Mutex::Mutex() {
	if ( 0 != pthread_mutex_init(&_mutex, NULL) ) {
		throw new MutexException();
	}
}

/* Mutex will always be valid, that is guaranteed
   loop on the destroy until is succeeds because the mutex
   might be locked by another thread and you don't want to
   destory it until the lock is released
 */
Mutex::~Mutex() {
	//while ( !destroy() );
	destroy();
}

bool Mutex::trylock() {
	return ( 0 == pthread_mutex_trylock(&_mutex) );
}

bool Mutex::lock() {
	return ( 0 == pthread_mutex_lock(&_mutex) );
}

bool Mutex::unlock() {
	return (0 == pthread_mutex_unlock(&_mutex)); 
}

bool Mutex::destroy() {
	return ( 0 == pthread_mutex_destroy(&_mutex));
}

}
